package org.example.myAop.dao.Impl;

import jakarta.annotation.Resource;
import org.example.myAop.dao.UserDao;
import org.example.myAop.entity.User;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 莫磊
 * @date 2025/7/31
 * @description
 */
@Repository
public class UserDaoImpl implements UserDao {

	@Resource
	JdbcTemplate jdbcTemplate;

	@Override
	public int addUser(List<User> list) {
		String sql = "insert into user (name, age) values (?,?)";
		List<Object[]> collect = list.stream().map(user -> new Object[]{user.getName(), user.getAge()}).collect(Collectors.toList());
		// 返回的是每一条执行结果影响的行数，也就是是否成功，1：成功，0：失败
		int[] ints = jdbcTemplate.batchUpdate(sql, collect);
		return Arrays.stream(ints).sum();
	}

	@Override
	public int updateUser(List<User> list) {
		String sql = "update user set name = ?, age = ? where id = ?";
		List<Object[]> collect = list.stream().map(user -> new Object[]{user.getName(), user.getAge(), user.getId()}).collect(Collectors.toList());
		int[] ints = jdbcTemplate.batchUpdate(sql, collect);
		return Arrays.stream(ints).sum();
	}

	@Override
	public List<User> queryUser() {
		String sql = "select * from user";
		List<User> query = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(User.class));
		return query;
	}
}
